const fs = require('fs');
const path = require('path');
var exec = require('child_process').exec;
const LOG = require('./console');
const ProgressBar = require('progress');

exports.CommandJstack = {
    paramss: {},
    step1Init: (options) => {
        const params = {
            pid: options.pid,
            interval: options.interval,
            total: options.total,
            storagePath: options.dir,
            namePrefix: options.name | ''
        }
        LOG.consoleInfo(`Stack trace info of process[pid:${params.pid}]`);
        LOG.consoleInfo(`****PLAN: interval-${params.interval},total times: ${params.total},may be cost :${params.interval * params.total} s`);
        var bar = new ProgressBar(':bar :current/:total', {total: Number(params.total)});
        var times = 0;
        var jstackInterval = setInterval(() => {
            var thisTimesFile = params.storagePath + '/'+ params.namePrefix + '_jstack_by_jaer_'+ times + '.log';
            exec('jstack -l '+ params.pid + ' > '+thisTimesFile, function(err, stdout, stderr) {
                // LOG.consoleInfo('Stack trace info to file :' + thisTimesFile + ' successfuly!');
                bar.interrupt( 'Generate to file '+ thisTimesFile + ' successful!');
                bar.tick();
                if (times == params.total) {
                    LOG.consoleInfo(`All done! Successfuy get stack trace info of process[pid:${params.pid}]`);
                }
            });
            times++;
            if (times == params.total) {
                clearInterval(jstackInterval);
            }
        }, params.interval * 1000);
        setTimeout(() => {
        }, params.total * params.interval * 1000);
    }
}